package io.kimmking.chatoom.server.config;

import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
@Data
@NoArgsConstructor
@AllArgsConstructor
public class NettyServerConfig {

    @Value("${km.netty.server.port:8088}")
    private Integer port;

    @Value("${km.netty.server.workerLoopGroups:16}")
    private Integer workerLoopGroups;

    @Value("${km.netty.server.bossLoopGroups:1}")
    private Integer bossLoopGroups;

    @Value("${km.netty.server.soBacklog:128}")
    private Integer soBacklog;

    @Value("${km.netty.server.soKeepAlive:true}")
    private boolean soKeepAlive;

    private static String hostName = "127.0.0.1";

    /**
     * 管理全局的channel
     * GlobalEventExecutor.INSTANCE 全局事件监听器
     * 一旦通过add()方法将channel加入ChannelGroup，当channel连接失效之后，会自动进行移除操作
     */
    public final static ChannelGroup channelGroup
            = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    static {
        try {
            hostName = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static String getHostName() {
        return hostName;
    }
}
